import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isHttp } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'

NProgress.configure({ showSpinner: false });

const whiteList = ['/auth', '/404'];

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (!useUserStore().name) {
      isRelogin.show = true
      await useUserStore().getUserInfo().then(() => {
        isRelogin.show = false
      }).catch(err => {
        // ElMessage({ message: '登录失败!,请重新登录!', type: 'error', duration	: 1000 })
        // useUserStore().logOut().then(() => {
        //  setTimeout(() => {
        //   loginAgain()
        //  })
        // }, 1000)
      })
    }
    if (to.path === '/') {
      // 有token,访问根路径,默认路径进入首页
      next('/transportOrderManagement/transportOrderList')
      NProgress.done()
    }else if(to.path !== '/auth') {
      // 除了auth授权页面其它页面正常访问
      next()
      NProgress.done()
    }else {
      // 有token,非法访问auth进行拦截
      next('/404')
      NProgress.done()
    }
  } else {
    if (to.path == '/' && to.query.authCode) {
      next(`/auth?authCode=${to.query.authCode}`)
      NProgress.done()
    }else if (whiteList.indexOf(to.path) !== -1) {
      if(to.path === '/auth' && !to.query.authCode){
        loginAgain()
      }else {
        // 不能省略白名单步骤,auth页面必须放行
        next()
      }
      NProgress.done()
    } else {
      // 没有token,不能访问权限页面
      loginAgain()
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})


function loginAgain() {
    const client_id = 'suiteihfzbkbsm0thrqgi'
    const redirectUri = encodeURIComponent(window.location.origin)
    const scope = encodeURIComponent('openid corpid')
    const state = 'bituo' // 状态值,用于防止CSRF攻击
    const loginUrl = `https://login.dingtalk.com/oauth2/auth?redirect_uri=${redirectUri}&response_type=code&client_id=${client_id}&scope=${scope}&prompt=consent&state=${state}`
    location.href = loginUrl
}